package ru.nsu.fit.client.core.soap;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import ru.nsu.fit.client.core.log_manager.realization.KernelLogManager;

import java.util.Map.Entry;
import java.util.Set;

public class SOAPExecutor {
	public static SoapObject executeSOAP(String wsdlLocation, String namespace, String methodName, Set<Entry<String, String>> properties) throws Exception
	{
		SoapObject request = new SoapObject(namespace, methodName); 
		String soapAction = '"' + namespace + methodName + '"';
		
		if (properties != null)
		{
			SoapObject arg0 = new SoapObject(namespace, methodName);
			for(Entry<String, String> entry: properties)
			{
				PropertyInfo info = new PropertyInfo();
				info.setType(String.class);
				info.setName(entry.getKey());
				info.setValue(entry.getValue());
				arg0.addProperty(info);
			}
			request.addProperty("arg0", arg0);
		}
	     
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.implicitTypes = true;
        envelope.setOutputSoapObject(request);
 
        HttpTransportSE ht = new HttpTransportSE(wsdlLocation);
        ht.debug = true;
        ht.call(soapAction, envelope);

        if (ht.debug)
        {
            KernelLogManager.print("Response: \n" + ht.responseDump + "\n");
        }

		return (SoapObject) envelope.getResponse();
	}
}
